<template>
	<view style="padding: 10px;">
		<uni-forms ref="form" :rules="{}">
			<view v-for="(item,index) in type == 1?entity.imglist:entity.MediumList" :key="index">
				<view v-if="item.Mtype==='audio'">
					<eliseAudio audioId="audio1" :url="item.Murl" audioColor="#68d7bb" :durationS="item.duration"
						ref="eliseAudio" v-if="item.Mtype==='audio'" style="margin-bottom: 10px;"></eliseAudio>

					<uni-icons type="trash" v-if="item.Mtype==='audio'" @click="imgDel(item,index)" class="color"
						size="20" color="red"></uni-icons>
				</view>
			</view>
			<uni-forms-item name="">
				<uni-grid :column="3" :showBorder="false">
					<view v-for="(item,index) in type == 1?entity.imglist:entity.MediumList" :key="index">
						<uni-grid-item v-if="item.Mtype==='image'||item.Mtype==='video'">
							<image :src="item.Murl" style="width: 100%;height: 100%;" mode="aspectFit"
								@click="lookimg(type == 1?entity.imglist:entity.MediumList,index)"
								v-if="item.Mtype==='image'"></image>
							<view class="video" v-if="item.Mtype==='video'"
								@click="lookimg(type == 1?entity.imglist:entity.MediumList,index)">
								<uni-icons type="videocam-filled" size="36" color="#ccc"></uni-icons>
							</view>

							<uni-icons v-if="type == 1?entity.imglist.length>1:entity.MediumList.length>0"
								type="trash-filled" @click="imgDel(item, index)" class="color" size="20" color="#fff"
								style="position: absolute; right: 5%;top: 5%;z-index: 9; background-color:#ef0a0a; border-radius: 5px;">
							</uni-icons>
						</uni-grid-item>
					</view>
				</uni-grid>
			</uni-forms-item>
			<uni-forms-item v-for="item in PropData" :key="item.ControlKey" :label="item.ControlName"
				:name="item.ControlKey">
				<text v-if="item.ControlName == '楼层' && isText==true "
					style="color:red;font-size:22rpx">*仅可输入"符号和字符"</text>
				<view v-if="item.ControlName == '楼层'"
					style="display: flex;border:1px solid #E5E5E5;border-radius: 10rpx;padding: 12rpx;">
					<!-- <uni-easyinput placeholder="请输入" type="number" @input="propInput($event,item)"
						v-model="entity[item.ControlKey]" suffixIcon="层"></uni-easyinput> -->
					<input placeholder-style="font-size:23rpx;padding-left:8rpx" placeholder="请输入(如负一层请输入 -1 )"
						type="text" @input="propInput($event,item)" v-model="entity[item.ControlKey]" suffixIcon="层"
						@focus="propInputFocus" @blur="propInputBlur"></input>
				</view>
				<view v-if="item.ControlType == 'select'">
					<uni-data-select @change="propItemChange($event,item)" v-model="entity[item.ControlKey]"
						:localdata="item.CVdata">
					</uni-data-select>
					<uni-easyinput @confirm="customize(item)" @blur="customize(item)" placeholder="输入后点击键盘确认进行添加"
						v-if="entity[item.ControlKey]=='自定义'" v-model="item.customize">
					</uni-easyinput>
				</view>
				<uni-easyinput placeholder="请输入" v-if="item.ControlType == 'input'&&item.ControlName!='楼层'"
					@input="propInput($event,item)" v-model="entity[item.ControlKey]"></uni-easyinput>
				<view class="formCheck" v-if="item.ControlType == 'checkBox'">
					<view class="input" @click="openCheck(item)" style="width: 100%;">
						<view class="value" v-if="entity[item.ControlKey]">{{entity[item.ControlKey]}}</view>
						<view class="noValue" v-else>请选择</view>
					</view>
					<view>
						<uni-icons @click="openCheck(item)" v-if="!entity[item.ControlKey]" type="bottom" size="14"
							color="#989898"></uni-icons>
						<uni-icons @click="clearCheckBoxSelect(item)" v-else type="clear" size="24"
							color="#c0c4cc"></uni-icons>
					</view>
					<CheckBoxSelect :ref="'CheckBoxSelect'+item.ControlKey"
						@confirm="CheckBoxSelectConfirm($event,item)" @add="addItem" />
				</view>
			</uni-forms-item>
			<uni-forms-item name="" style="position: relative;">
				<uni-easyinput type="textarea" autoHeight v-model="entity.Content" placeholder="描述内容" :maxlength="-1">
				</uni-easyinput>
			</uni-forms-item>
		</uni-forms>
		<button style="margin-top: 10px;" type="warn" @click="confirm">保存</button>
		<!-- 录音 -->
		<uni-popup ref="audio" type="bottom" @close="audioClose" style="position: relative;" :is-mask-click="false"
			@maskClick="audioClose">

			<nb-voice-record @startRecord="start" @endRecord="end" @cancelRecord="cancel" btnDefaultText="录音"
				:popupFixBottom="250" btnHoverBgcolor="red" btnHoverFontcolor='#fff'
				:btnStyle="{width:'70px',height:'70px',background: 'red',color:'#fff',borderRadius: '50%',fontSize:'16px'}"
				style="float: left;margin-left: calc(50% - 35px);margin-bottom: 100rpx;">
			</nb-voice-record>
		</uni-popup>
		<!-- 常用语 -->
		<uni-popup ref="expression" type="bottom">
			<uni-list>
				<uni-list-item title="列表文字" v-for="item in 10" :key="item" clickable
					@click="expressionClick(item)"></uni-list-item>
			</uni-list>
		</uni-popup>
		<ImageView ref="ImageView" @setEdit="setEditObj" @close="imageClose" :parentObj="{ ...this }"></ImageView>
		<videoView ref="videoView"></videoView>
	</view>
</template>

<script>
	import ImageView from '@/components/ImageView.vue'
	import videoView from '@/components/videoView.vue'
	import eliseAudio from '@/components/elise-audio/elise-audio.vue'
	import CheckBoxSelect from '@/components/checkBoxSelect.vue'
	import {
		setStorageEntityProjectXmRwIdObj
	} from '@/utils/tools.js'
	export default {
		components: {
			ImageView,
			eliseAudio,
			videoView,
			CheckBoxSelect
		},
		data() {
			return {
				isText: false,
				options: null,
				entity: {},
				type: 1,
				index: 0,
				TaskId: '',
				ProjectId: '',
				// 判断是编辑页面过来的编辑还是报告页面过来的编辑 走不同的接口逻辑
				dataUrl: "",
				editObj: '',
				PropData: [],
				isUp: false, //是否上传中
			}
		},
		// 监听顶部左上角返回事件
		onBackPress() {
			// 移出上传的uploadImgList
			uni.removeStorageSync('editImgList') //返回清空缓存存储的画好的图片数据
			this.$store.commit('clearImageList') //返回清空vuex存储的画好的图片数据
		},
		async onShow() {
			// 在uniapp中调用Android插件
			if (this.$store.state.editLocalImg.Murl !== undefined) {
				console.log('打印最终需要渲染的图片---', this.entity.MediumList)
				this.entity.MediumList.forEach(item => {
					if (item.name === this.$store.state.editLocalImg.name) {
						item.Murl = this.$store.state.editLocalImg.Murl
					}
				})
				if (this.options) {
					this.isUp = true
					await setTimeout(async () => {
						uni.showLoading({
							title: '上传中'
						})
						await uni.uploadFile({
							url: this.$url +
								`Base_Manage/Upload/OssUploadFileByForm?ProjectId=${this.options.data.ProjectId}&TaskId=${this.options.data.TaskId}`,
							// ?ObjectKey=${strFileName}
							filePath: this.entity.MediumList[0].Murl,
							name: 'file',
							header: {
								'Authorization': uni.getStorageSync('tokenKey')
							},
							formData: {

							}
						}).then(async response => {
							let [error, res] = response;
							let result = JSON.parse(res.data)
							this.entity.MediumList[0].Murl = result.Url
							await setTimeout(() => {
								uni.hideLoading()
								uni.showToast({
									title: '上传成功',
									icon: 'none'
								});
								this.isUp = false
							}, 500)
						})
					}, 1)
				}
				console.log('获取最终处理好后的编辑图片列表', this.entity.MediumList)
			}
		},
		onLoad(options) {
			this.options = options
			// let newEditLoaclImageList = JSON.parse(uni.getStorageSync('editLocalImgList'))
			if (options.data) {
				let newObj = decodeURIComponent(options.data)
				this.options.data = JSON.parse(newObj)
				this.entity = JSON.parse(newObj)
				console.log(this.entity.PropData);
			}

			console.log('获取viewCOpy传递过来的editPage参数--------------------', this.options, options)
			// 判断是编辑页面过来的编辑还是报告页面过来的编辑 走不同的接口逻辑
			if (options.interface) this.dataUrl = 'Base_ProjectWork/Base_Project/UpdateProjectTakeJsonData'
			else this.dataUrl = 'Base_ProjectWork/Base_Project/UpdateTakeJson'
			// type 1 本地 2 私人 3 图片进入需查询数据
			this.type = options.type
			this.index = options.index
			this.TaskId = options.id
			this.ProjectId = options.pid
			if (this.type == 1 || this.type == 2) {
				console.log('走2')
				this.entity.PropData.forEach(item => {
					this.$set(this.entity, item.ControlKey, item.DefaultValue)
				})
			} else if (this.type == 3) {
				console.log('走3详情')
				this.getTheData()
			}
			this.PropData = uni.getStorageSync('propData') || []
			if (this.PropData.length == 0) {
				this.$http('Base_ProjectWork/Base_Project/GetTakeNotesTypeData').then(res => {
					console.log(res);
					if (res.Success) {
						this.PropData = res.Data
						uni.setStorageSync('propData', res.Data)
					}
				})
			}
			let entity = this.entity
			let arr = [...entity.PropData, ...this.PropData]
			let newArr = []
			entity.PropData.forEach((item, index) => {
				let arr = [...this.PropData[index].CVdata, ...item.CVdata]
				let objn = {}
				let arrn = []
				arr.forEach(val => {
					if (!objn[val.value]) {
						objn[val.value] = 1
						arrn.push(val)
					} else {
						objn[val.value] += 1
					}
				})
				item.CVdata = arrn
				newArr.push(item)
			})
			this.entity = entity
			this.PropData = this.entity.PropData
		},
		methods: {
			addItem(list) {
				uni.setStorageSync('propData', this.PropData)
			},
			imageClose() {
				this.navShow = true
			},
			// 存储画图数据
			setEditObj(data) {
				console.log('获取编辑页面过来的图片编辑存储画图数据', data);
				if (data !== null) {
					uni.setStorageSync('editImgList', data)
				} else {
					uni.setStorageSync('editImgList', this.editObj)
				}
			},
			// 楼层输入函数
			propInput(e, item) {
				item.DefaultValue = e.detail.value;
				const inputRule = /[^\d_-]/g //只能输入数字和部分特殊字符
				this.$nextTick(function() { //针对楼层
					this.entity[item.ControlKey] = e.detail.value.replace(inputRule, '');
				})
			},
			// 楼层输入获取焦点提示
			propInputFocus() {
				console.log('获取焦点了')
				this.isText = true
			},
			// 楼层输入失去焦点
			propInputBlur() {
				this.isText = false
			},
			clearCheckBoxSelect(item) {
				item.DefaultValue = ''
				this.$set(this.entity, item.ControlKey, '')
			},
			CheckBoxSelectConfirm(e, item) {
				item.DefaultValue = e.join(',')
				// this.entity[item.ControlKey] = item.DefaultValue
				this.$set(this.entity, item.ControlKey, item.DefaultValue)
			},
			openCheck(item) {
				this.$refs['CheckBoxSelect' + item.ControlKey][0].open(item.CVdata, item.DefaultValue)
			},
			getTheData() {
				this.$http('Base_ProjectWork/Base_Project/GetTakeNotesData', {
					"ProjectId": this.ProjectId,
					"TaskId": this.TaskId,
					"TakeNotesId": this.entity.TakeNotesId,
					"UserId": uni.getStorageSync('userInfo').Id
				}).then(res => {
					console.log(res);
					if (res.Success) {
						this.entity = res.Data
						this.entity.PropData.forEach(item => {
							this.$set(this.entity, item.ControlKey, item.DefaultValue)
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: res.Msg
						})
					}
				})
			},
			//删除图片
			imgDel(item, index) {
				if (this.isUp) {
					return
				}
				console.log('editPage', item, index, this.entity, this.type)
				if (this.type == 1) {
					// #ifdef H5
					this.entity.imglist.splice(index, 1)
					// #endif
					// #ifdef APP
					uni.removeSavedFile({ //删除本地文件 
						filePath: this.entity.imglist[index].Murl,
						success: () => {
							this.entity.imglist.splice(index, 1)
						},
						complete: (resa) => {
							console.log(resa)
						}
					});
					// #endif
				} else {
					this.entity.MediumList.splice(index, 1)
				}
			},
			// 自定义
			customize(item) {
				if (item.CVdata.findIndex((im) => im.value == item.customize) !== -1)
					return this.$message.error("当前添加项已存在于列表中");
				item.CVdata.unshift({
					value: item.customize,
					text: item.customize,
				});
				this.$set(this.entity, item.ControlKey, item.customize);
				item.DefaultValue = item.customize;
				item.customize = "";
			},
			// 动态列表选择
			propItemChange(e, item) {
				item.DefaultValue = e
			},
			// 查看视频
			lookvideo(path) {
				this.$refs.videoView.open(path)
			},
			// 查看图片
			lookimg(path, index) {

				if (this.isUp) {
					return
				}
				// 判断是否是从报告页面过来的编辑图片。。如果是  先不让编辑图片  后续根据需求显示即可
				if (this.options.reportType === 'true') return

				path.forEach(item => {
					let strFileName = item.Murl.substring(
						item.Murl
						.lastIndexOf("/") + 1)
					item.name = strFileName

				})
				console.log('图片名称循环处理结果', path)
				let obj = {
					imageList: path,
					current: index,
					PropData: this.entity.PropData,
					type: 'edit',
					Content: this.entity.Content
				}
				console.log('获取图片数组', path, index, this.entity, obj);

				console.log(this.options);
				this.$refs.ImageView.open(obj, this.options)
				this.editObj = JSON.stringify({
					content: path,
					vix: index
				})
			},
			// 常用语选用
			expressionClick(item) {
				this.$set(this.entity, 'Content', item)
				this.$refs.expression.close()
			},
			// 录音
			audioOpen() {
				uni.hideTabBar()
				this.$refs.audio.open()
			},
			start() {
				console.log('开始录音')
				// 开始录音
			},
			end(event) {
				this.audioClose()
				console.log(event)
				var audio1 = uni.createInnerAudioContext();
				audio1.src = event.tempFilePath
				var duration = 0
				setTimeout(() => {
					duration = audio1.duration.toFixed(2)
					var strFileName = event.tempFilePath.substring(event.tempFilePath.lastIndexOf("/") + 1)

					this.entity.imglist.push({
						Mtype: 'audio',
						name: strFileName,
						audioplay: true,
						duration: audio1.duration.toFixed(2),
						Id: new Date().getTime(),
						Murl: event.tempFilePath
					})
					console.log(this.entity.imglist)
					console.log(event)
				}, 100)

				// 结束录音并处理得到的录音文件
				// event中，app端仅有tempFilePath字段，微信小程序还有duration和fileSize两个字段
			},
			cancel() {
				console.log('取消录音')
				// 用户取消录音
			},
			audioClose() {
				uni.showTabBar()
				this.$refs.audio.close()
			},
			// 保存
			confirm() {
				if (this.isUp) {
					return
				}
				console.log(this.entity);

				if (!this.entity.Content) return uni.showToast({
					icon: 'none',
					title: '请填写描述'
				})
				if (this.type == 1) {
					let arr = JSON.parse(uni.getStorageSync('fromdata'))
					arr.splice(this.index, 1, this.entity)
					uni.setStorageSync('fromdata', JSON.stringify(arr))
					this.backPage()
				} else {
					uni.showLoading()
					console.log('获取传递的参数------------------------', this.entity)
					// 更新缓存EntityProjectXmRwIdObj对象
					let obj = {
						xmId: this.options.xmId,
						rwId: this.options.rwId,
						xmName: this.options.xmName,
						rwName: this.options.rwName,
					}

					setStorageEntityProjectXmRwIdObj(obj)

					this.$http(this.dataUrl, {
						"ProjectId": this.ProjectId,
						"TaskId": this.TaskId,
						TakeNotesList: [this.entity]
					}).then(res => {
						uni.hideLoading()
						if (res.Success) {
							this.backPage()
						} else {
							uni.showToast({
								icon: 'none',
								title: res.Msg
							})
						}
					})
				}
			},
			backPage() {
				uni.showToast({
					icon: 'none',
					title: '操作成功'
				})
				let pages = getCurrentPages(); //获取所有页面栈实例列表
				let nowPage = pages[pages.length - 1]; //当前页页面实例
				let prevPage = pages[pages.length - 2]; //上一页页面实例
				console.log('获取上个页面inspection页面栈prevPageprevPageprevPage', prevPage)
				// prevPage.$vm.address = e;//给上个页面的变量赋值
				prevPage.$vm.getDataList(); //调用上个页面的方法
				setTimeout(() => {
					uni.navigateBack()
				}, 1000)
			}
		}
	}
</script>

<style>
	.video {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-sizing: border-box;
		border: 1px solid #ccc;
	}

	.formCheck {
		width: 100%;
		flex: 1;
		border: 1px solid #e5e5e5;
		box-sizing: border-box;
		border-radius: 4px;
		padding: 0 5px;
		padding-left: 10px;
		position: relative;
		display: flex;
		align-items: center;
		border-bottom: solid 1px #e5e5e5;
		-webkit-user-select: none;
		user-select: none;
		flex-direction: row;
		max-width: 100%;
		height: 35px;
		color: #6a6a6a;
		font-size: 12px;

		.input {
			flex: 1;
			max-width: 100%;

			.value {
				width: 460rpx;
				font-size: 14px;
				color: rgb(58, 58, 58);
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}
		}
	}
</style>